#############################
# Overall ATT: Crime Rates
#############################

rm(list=ls())

library(Hmisc)
library(readstata13)
library(foreign)
library(tidyverse)
library(did)
library(ggplot2)
set.seed(1111)

#sink("10_overall_all_rates.txt")

############################
# Read and prepare data 
############################

# Load point estimates and standard errors
d1 <- read.table("~/Dropbox/Immigration Chile/02_analysis/overallATT_5.txt",comment.char="")
d2 <- read.table("~/Dropbox/Immigration Chile/02_analysis/overallATT_6.txt",comment.char="")
d3 <- read.table("~/Dropbox/Immigration Chile/02_analysis/overallATT_7.txt",comment.char="")
d4 <- read.table("~/Dropbox/Immigration Chile/02_analysis/overallATT_8.txt",comment.char="")

# Prepare multiple comparisons
rat_all = d1$V1[1]/d1$V1[2]
rat_all_cov = d2$V1[1]/d2$V1[2]
rat_haiti = d3$V1[1]/d3$V1[2]
rat_haiti_cov = d4$V1[1]/d4$V1[2]

pv_rat_all = 2*pnorm(q=rat_all, lower.tail=F)
pv_rat_all_cov = 2*pnorm(q=rat_all_cov, lower.tail=T)
pv_rat_haiti = 2*pnorm(q=rat_haiti, lower.tail=T)
pv_rat_haiti_cov = 2*pnorm(q=rat_haiti_cov, lower.tail=T)

p1 <- c(pv_rat_all,pv_rat_all_cov)
p2 <- c(pv_rat_haiti,pv_rat_haiti_cov)

# Corrected p-values visas from all countries on crime rates (Table A17)
round(p.adjust(p1, "bonferroni"),3)

# Corrected p-values visas from Haiti on crime rates (Table A17)
round(p.adjust(p2, "bonferroni"),3)

# Prepare Table 17_concerns
pe_haiti = c(d3[1,], d4[1,])
pe_all = c(d1[1,], d2[1,])
se_haiti = c(d3[2,], d4[2,])
se_all = c(d1[2,], d2[2,])

round(pe_haiti,3)
round(se_haiti,3)
round(pe_all,3)
round(se_all,3)

# Table A17 concerns
results_rates <- rbind(round(pe_haiti,3),round(se_haiti,3),round(pe_all,3),round(se_all,3)) 
column <- rbind("visas from haiti","","visas from all countries","") 
results_rates <- cbind(column,results_rates)
write.table(results_rates, "tableA17_rates.txt", sep="\t")

sink()
